package com.wxy.web.filter;

import com.wxy.common.utils.ip.IpUtils;
import com.wxy.web.model.Module;
import com.wxy.web.model.User;
import com.wxy.web.model.Userlog;
import com.wxy.web.security.authentication.JwtTokenUtil;
import com.wxy.web.service.IModuleService;
import com.wxy.web.service.IUserService;
import com.wxy.web.service.IUserlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class UserlogFilter extends OncePerRequestFilter
{
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserlogService userlogService;
    @Autowired
    private IModuleService  moduleService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        System.out.println( "===========\n" + request.getRequestURI());
        Userlog log = new Userlog();

        log.setRequestIp(IpUtils.getIpAddr(request));
        log.setRequestMethod(request.getMethod());

        //获取username
        String header = request.getHeader(jwtTokenUtil.getTokenHeader());
        if (header == null || !header.startsWith(jwtTokenUtil.getTokenPrefix())) {
            chain.doFilter(request, response);
            return;
        }
        String token = header.replace(jwtTokenUtil.getTokenPrefix(), "").trim();
        String username = null;
        try {
            username = jwtTokenUtil.getUsernameFromToken(token);
        } catch (Exception e) {
            chain.doFilter(request, response);
            return;
        }
        User user = userService.getByUsername(username);
        if(user != null){
            log.setUserId(user.getId());
        }

        Module module = moduleService.getByUri(request.getRequestURI());
        if(module != null)
        {
            log.setModuleId(module.getId());
        }else{
            module = new Module();
            module.setUrl(request.getRequestURI());
            moduleService.save(module);
            log.setModuleId(module.getId());
        }

        log.setCreateTime(LocalDateTime.now());

//        if(request.getMethod() == "GET")
//            log.setRequestParam(request.getQueryString());
//        else if(request.getMethod() == "POST")
//            log.setRequestParam(request.getParameterMap().toString());

        userlogService.save(log);

        chain.doFilter(request, response);
    }
}
